#include "linkview.h"
#include <QDebug>
#include <QGraphicsRectItem>


class CommandAdd : public QUndoCommand
{
public:
    CommandAdd(Node *a, Node *b, QUndoCommand *parent = nullptr)
        : QUndoCommand(parent), pre(a), cur(b) {}

    void undo() override
    {
        pre->next=cur->next;
        cur->next=NULL;
    }

    void redo() override
    {
        cur->next=pre->next;
        pre->next=cur;
    }

private:
    Node *pre, *cur;
};


class CommandDel : public QUndoCommand
{
public:
    CommandDel(Node *a, Node *b, QUndoCommand *parent = nullptr)
        : QUndoCommand(parent), pre(a), cur(b) {}

    void undo() override
    {
        cur->next=pre->next;
        pre->next=cur;
    }

    void redo() override
    {
        pre->next=cur->next;
        cur->next=NULL;
    }

private:
    Node *pre, *cur;
};

LinkView::LinkView(QWidget *parent) : QGraphicsView(parent)
{
    list = new Node();
    list->next=NULL;
    scene = new QGraphicsScene(this);
    setScene(scene);
}

bool LinkView::add(int ind, int num)
{
    if(ind<0)return false;
    auto head = list;
    int i=ind;
    while(ind-- && head){
        head=head->next;
    }
    if(!head)return false;
    auto newNode = new Node();
    newNode->next=NULL;
    newNode->val=num;
    newNode->ind=i;
    stack.push(new CommandAdd(head, newNode));
    paint();
    return true;
}

bool LinkView::del(int ind, int num)
{
    if(ind<0)return false;
    auto head = list->next;
    auto pre = list;
    while(ind-- && head){
        pre=head;
        head=head->next;
        if(head==NULL)break;
    }
    if(!head)return false;
    stack.push(new CommandDel(pre, head));
    paint();
    return true;
}

void LinkView::paint()
{
    qDebug()<<"paint"<<endl;
    scene->clear();
    int pos = 0;
    for(auto pt = list->next;pt;pt=pt->next){
        qDebug()<<pt->ind<<", "<< pt->val<<endl;

        QGraphicsSimpleTextItem *textItem = new QGraphicsSimpleTextItem(QString("%1").arg(pt->val));
        textItem->setPos(pos, 3);
        scene->addItem(textItem);

        // 创建一个箭头（使用QGraphicsLineItem表示）
           QGraphicsLineItem *arrow = new QGraphicsLineItem();
           arrow->setLine(pos+11, 10, pos+20, 10); // 设置线的起点和终点，即箭头的方向
           arrow->setPen(QPen(Qt::red, 2)); // 设置线的颜色和宽度

       // 将箭头添加到场景中
       scene->addItem(arrow);

       pos+=21;

    }
}
